package sicnu.cs.aps.security.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import sicnu.cs.aps.domain.entity.User;
import sicnu.cs.aps.mapper.UserMapper;

import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {
    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 校验账号
        // 邮箱登录
        String emailChar = "@";
        User user;
        if (username.contains(emailChar)) {
            user = userMapper
                    .findOptionalByEmail(username)
                    .orElseThrow(() -> new UsernameNotFoundException("Cannot find username"));
        }// 账号/手机登录
        else {
            user = userMapper
                    .findOptionalByUsername(username)
                    .orElseThrow(() -> new UsernameNotFoundException("Cannot find username"));
        }
        return user;
    }
}




